﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Twin
{
    class StrBytes
    {
        /**
         * 16进制字符串转换为字符串
         *
         * @param s
         * @return
         */

        public static string HexToStr(string s)
        {
            if (s == null || s.Equals(""))
            {
                return null;
            }
            s = s.Replace(" ", "");

            string strTemp = "";
            byte[] b = new byte[s.Length / 2];
            for (int i = 0; i < s.Length / 2; i++)
            {
                strTemp = s.Substring(i * 2, 2);
                b[i] = Convert.ToByte(strTemp, 16);
            }
            //按照指定编码将字节数组变为字符串
            return System.Text.Encoding.UTF8.GetString(b);
        }
        
        //======================================
        //根据%，将arr指向的ss个字节,转换成字符串
        //======================================
        /*
        public static String FormatBytes(String sFmt,byte[] arr,int ss)      //,int bit_start,int ss)
        {
            String sTmp="";

            switch(sFmt)
            {
                case "s":			//中文或英文
		            sTmp=Bytes2Str(arr,ss);
                    break;
                case "d":                  //十进制
		            sTmp=Bytes2Decimal(arr,ss);
                    break;
                case "f":	
		            sTmp=Bytes2Float(arr);
                    break;
                case "x":
		            sTmp="&H" + Bytes2Hex(arr,ss);
                    break;
                case "l":			//链接
		            sTmp=Bytes2Str(arr,ss);
                    break;

                    //case "%b":	
		    //sTmp=Byte2Binary(arr,bit_start,ss);
                    //break;
            }
	    return sTmp;
        }*/

        //=================================
        // 0x12,0x34,0x56 ==> "123456"
        //=================================
        public static String Bytes2Hex(byte[] arr, int size){
            String s="";
            for(int i=0; i<size; i++){
                if(i<arr.Length){
                    s += Hex88(arr[i]);   // Convert.ToString(b[i], 16); //String.Format("%02X", arr[i]);  // + s;
                }
                else{
                    s +="00";
                }
	        }
	    //s="&H"+s;
	    return s;
        }
    
        
        //结果限制长度为2
        public static String Hex88(byte b){

            String s = Convert.ToString(b, 16).ToUpper();
            if (s.Length == 1) {
                s = "0" + s;
            }
            return s;
            //String s = String.Format("%02X", x);
            //return s.substring(s.length()-2, s.length());
        }
        
        /*
    
        //结果长度限制为4
        public static String Hex8888(int x){
            String s = String.Format("%04X", x);
            return s.substring(s.length()-4, s.length());
        }
    
        //结果不限制长度
        public static String Hex(int x){
            String s = String.Format("%X", x);
            return s;
        }
        */

        //=================================
        //  "&H123456" ==> 0x12,0x34,0x56
        //=================================
        public static byte[] Hex2Bytes(String sHex) 
        {  
	        if (sHex == null || sHex == "") {  
	            return null;  
	        }  
	        sHex = sHex.ToUpper(); 
	    
	        int length = sHex.Length / 2; 
	        char[] hexChars = sHex.ToCharArray();  
	        byte[] d = new byte[length];  
	        for (int i = 0; i < length; i++) {  
	            int pos = i * 2;  
	            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
	        }  
	        return d;  
        } 
	
        private static byte charToByte(char c) {  
	        byte b = (byte) "0123456789ABCDEF".IndexOf(c);
            return b;
        }  

    
        //在一个byte中获取bits代表的值
        public static byte getBits(byte c,int start_bit,int size)
        {
            byte mask;
        
            c>>=start_bit;
            mask = (byte)(0xff>>(8-size));
            return (byte)(c & mask);
        }

        //设置c中bits,保持其他bits不变
        public static byte setBits(byte newB, byte oldB,int start_bit,int size)
        {
            byte mask, mask1;
        
            // 11111111
            //newB >>= (8-size);    // 00000011
            //newB <<= start_bit;   // 00000110
        
            // 11111001
            mask = (byte)(0xff>>(size+start_bit));  // 00011111 
            mask <<= size+start_bit;                // 11111000
            mask1 = (byte)(0xff>>(8-start_bit));    // 00000001
            mask = (byte)(mask|mask1);              // 11111001
        
            return (byte)((oldB & mask)| (newB &(~mask)));
        }
    
        public static byte testbit(byte var,byte bit)
        {
            return (byte)((var) & (1<<(bit)));
        }

        /*
        public static byte setbit(byte var, byte bit)
        {
	        if(bit==0){
                return ((var)|= 0x01);
	        }else{
                return ((var)|= (1<< (bit)));
	        }
        }

        public static byte clrbit(byte var, byte bit)
        {
	        if(bit==0){
                return ((var) &= 0xfe);
	        }else{
                return ((var) &= ~(1<< (bit)));
	        }
        }


        public static void FillArrayWith(byte[] arr, byte c, int size)
        {
            for(int i=0; i<arr.length; i++){
                arr[i]=c;
            }
        }
    //===========================  xxx To Str (Read) ===============================

        //=================================
        // 转化为中文或英文
        //=================================
        private static String Bytes2Str(byte[] arr,int size)
        {
            byte[] buf = new byte[2048];
        
            if(size>arr.length){size=arr.length;}
        
            FillArrayWith(buf,(byte)0,size);
	        System.arraycopy(arr, 0, buf, 0, size);
	        buf[size]='\0';
        
            return new String(arr); 
        }


        //=================================
        // 转化为十进制数
        //=================================
        private static String Bytes2Decimal(byte[] arr,int size)
        {
        
            byte[] buf = new byte[8];
            System.arraycopy(arr, 0, buf, 0, arr.length);
            buf = ArrayReverse(buf);    //C -> java
        
            long L = getLong(buf,0);
	        return String.valueOf(L); 
        }


        //=================================
        // 转化为浮点数
        //=================================
        private static String Bytes2Float(byte[] arr)
        {
            byte[] buf = new byte[4];
            System.arraycopy(arr, 0, buf, 0, arr.length);
            buf = ArrayReverse(buf);    //C -> java

            float f;
            // 从byte数组的index处的连续4个字节获得一个float  
            f = Float.intBitsToFloat(getInt(buf,0));
	        return String.valueOf(f); 
        }

        //=================================
        // 转化为二进制字符串
        //
        // start_bit 从0开始
        // *p=0x08,start_bit=3,size=1
        // ==>"1"
        //=================================
        public static String Byte2Binary(byte b, int start_bit, int size)
        {
            String sTmp="";
            byte c;
            int i,j;
        
	        i=start_bit;
	        j=0;
	        while(j++<size){
	            if(testbit(b,(byte)(i++))!=0){sTmp="1"+sTmp;}
	            else{sTmp="0"+sTmp;}
	        }
	        return sTmp; 
        }

        //=================================
        // 转化为Link字符串
        //=================================
        String Bytes2Link(byte[] arr)
        {
	        return new String(arr); 
        }

        //s: src
        //c: "#" 
        public static String StrBefore(String src, String c){
            if(src == null){
                return null;}
        
            //每一行均以“#”结尾;
            int pos = src.indexOf(c);           //("#");
            if(pos >= 0){
                src = src.substring(0, pos); }  //"#"不存在时，返回原串
            return src.trim();
        }

        public static String StrAfter(String src, String c){
            if(src == null){
                return null;}
        
            //每一行均以“#”结尾;
            int pos = src.indexOf(c);           //("#");
            if(pos >= 0){
                src = src.substring(pos + 1); }
            else{src = "";}                 //"#"不存在时，返回“”
            return src.trim();
        }
    
        public static String blankStr(int n)
        {
            String s="";
            int nBlank = 64;
            for(int i=0;i<nBlank;i++){
                s+=" ";
            }
            return s.substring(0,n);
        }
        

        //==============================================================================    
        //========================    To Bytes (Write)    ==============================
        //==============================================================================  
        public static byte[] Str2Bytes(String Str)     
        {
            //int nBytes;
    
            char[] chars = Str.toCharArray();
        
            CharBuffer charBuffer = CharBuffer.allocate(chars.length);
            charBuffer.put(chars);
            charBuffer.flip();
            //字符编码为字节数组
            Charset charset = Charset.forName("gbk");    //"utf-8":使用utf-8编码字符集;
            ByteBuffer byteBuffer = charset.encode(charBuffer);
            int len = byteBuffer.capacity();
            byte[] des = new byte[len];
            des = byteBuffer.array();
        
            return des;
        }

        private static byte[] ArrayReverse(byte[] arr)
        {
            byte[] t = new byte[arr.length];
        
            for(int i=0;i<arr.length;i++){
                t[i]=arr[arr.length-1-i];
            }
            return t;
        }
    
        public static String HexReverse(String sHex)
        {
            String s="";
            int len = sHex.length()/2;
            for(int i=0; i<len; i++){
                s = sHex.substring(i*2, i*2+2) + s;
            }
            return s;
        }
    */
    
    //==============================================================================    
        //从byte数组的index处的连续两个字节获得一个char  
        public static char getChar(byte[] arr, int index) 
        {  
            return (char) (0xff00 & arr[index] << 8 | (0xff & arr[index + 1]));  
        }
        //从byte数组的index处的连续两个字节获得一个  
        public static short getShort(byte[] arr, int index) {  
            //return (short) (0xff00 & arr[index] << 8 | (0xff & arr[index + 1]));
            return (short) (0xff00 & arr[index + 1] << 8 | (0xff & arr[index]));
        } 
 

/*
        // 从byte数组的index处的连续4个字节获得一个int  
        public static int getInt(byte[] arr, int index){  
            return  (0xff000000     & (arr[index+0] << 24))  |   
                    (0x00ff0000     & (arr[index+1] << 16))  |   
                    (0x0000ff00     & (arr[index+2] << 8))   |   
                    (0x000000ff     &  arr[index+3]);  
        }  
        // 从byte数组的index处的连续8个字节获得一个long  
        public static long getLong(byte[] arr, int index) {  
            return  (0xff00000000000000L    & ((long)arr[index+0] << 56))  |   
                    (0x00ff000000000000L    & ((long)arr[index+1] << 48))  |   
                    (0x0000ff0000000000L    & ((long)arr[index+2] << 40))  |   
                    (0x000000ff00000000L    & ((long)arr[index+3] << 32))  |  
                    (0x00000000ff000000L    & ((long)arr[index+4] << 24))  |   
                    (0x0000000000ff0000L    & ((long)arr[index+5] << 16))  |   
                    (0x000000000000ff00L    & ((long)arr[index+6] << 8))   |   
                    (0x00000000000000ffL    &  (long)arr[index+7]);  
        }
        //从byte数组的index处的连续8个字节获得一个double  
        public static double getDouble(byte[] arr, int index) {  
            return Double.longBitsToDouble(getLong(arr, index));  
        }
    
    
    //==============================================================================    
        // char转换为byte[2]数组  
        public static byte[] getByteArray(char c) 
        {  
            byte[] b = new byte[2];  
            b[0] = (byte) ((c & 0xff00) >> 8);  
            b[1] = (byte) (c & 0x00ff);  
            return b;  
        }  
        // short转换为byte[2]数组  
        public static byte[] getByteArray(short s) {  
            byte[] b = new byte[2];  
            b[0] = (byte) ((s & 0xff00) >> 8);  
            b[1] = (byte) (s & 0x00ff);  
            return b;  
        }  
        // int转换为byte[4]数组  
        public static byte[] getByteArray(int i) {  
            byte[] b = new byte[4];  
            b[0] = (byte) ((i & 0xff000000) >> 24);  
            b[1] = (byte) ((i & 0x00ff0000) >> 16);  
            b[2] = (byte) ((i & 0x0000ff00) >> 8);  
            b[3] = (byte)  (i & 0x000000ff);  
            return b;  
        }  
        // float转换为byte[4]数组  
        public static byte[] getByteArray(float f) {  
            int intbits = Float.floatToIntBits(f);//将float里面的二进制串解释为int整数  
            return getByteArray(intbits);  
        }  
        // long转换为byte[8]数组  
        public static byte[] getByteArray(long l) {  
            byte b[] = new byte[8];  
            b[0] = (byte)  (0xff & (l >> 56));  
            b[1] = (byte)  (0xff & (l >> 48));  
            b[2] = (byte)  (0xff & (l >> 40));  
            b[3] = (byte)  (0xff & (l >> 32));  
            b[4] = (byte)  (0xff & (l >> 24));  
            b[5] = (byte)  (0xff & (l >> 16));  
            b[6] = (byte)  (0xff & (l >> 8));  
            b[7] = (byte)  (0xff & l);  
            return b;  
        }  
        // double转换为byte[8]数组  
        public static byte[] getByteArray(double d) {  
            long longbits = Double.doubleToLongBits(d);  
            return getByteArray(longbits);  
        }
    
        //将二进制字符串转换回字节
        public static byte bit2byte(String bString)
        {
            byte result=0;
            for(int i=bString.length()-1,j=0;i>=0;i--,j++){
                result+=(Byte.parseByte(bString.charAt(i)+"")*Math.pow(2, j));
            }
            return result;
        }*/
    
        public static byte LoOfShort(short s)
        {
            return (byte)(s & 0x00ff);
        }
    
        public static byte HiOfShort(short s)
        {
            return (byte)(s>>8);
        }
    
    
        /*
        //======================================
        //                X字符的值
        // ‘0’-‘9’，‘A’-‘Z’，‘a’-'z'
        //
        // 返回：
        //    c正常：0-61
        //    c错误：0xFF
        //
        // 与ValueHex的区别：
        //  X():		A、a代表不同的值；etc.
        //  ValueHex: 	A、a代表相同值,etc。
        //======================================
        public static byte dX(String xChar)
        {
            char x = xChar.charAt(0);
            byte dx;

	    //dx=0;
	    if(x<='9'){
                dx=(byte)(x-'0');
            }
	    else if((x>='A')&&(x<='Z')){
	      dx=(byte)(x-'A'+('9'-'0'+1));
            }
	    else if((x>='a')&&(x<='z')){
	      dx=(byte)(x-'a'+('9'-'0'+1)+('Z'-'A'+1));
	    }
	    else{
                return (byte)0xFF;
            }
        
	    return dx;
        }

        //数字对应的X字符
        public static String sX(int x)
        {
            String[] X = new String[10+26+26];  //{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G"};
        
            int i = 0;
            int len = 10;
            while(i<len){
                X[i] = String.format("%c",i+'0');
                i++;
            }
        
            len = 10+26;
            int k=0;
            while(i<len){
                X[i] = String.format("%c",k+'A');
                i++;
                k++;
            }
        
            len = 10+26+26;
            k=0;
            while(i<len){
                X[i] = String.format("%c",k+'a');
                i++;
                k++;
            }
        
            return X[x];
        }
    
    
        // c 要填充的字符    
        //  length 填充后字符串的总长度    
        //  content 要格式化的字符串   
        //  格式化字符串，右对齐 
        //  
        public static String flushRight(char c, long length, String src){             
           String str = "";     
           //long cl = 0;    
           String sc = "";     
           if (src.length() > length){     
                str = src;     
           }else{    
                for (int i = 0; i < length - src.length(); i++){     
                    sc = sc + c;     
                }  
              }  
            str = src + sc;      
            return str;      
       }
 
        //（例如: dst=1001,1002>）
        // sBegin = "dst="; sEnding = ">"
        // BodyStr中替换指定特征的字符串
        public static String replaceWith(String src, String sBegin, String sEnding, String sSetting){
        
            String sHead = "";
            String sTail = "";
            int pos = src.indexOf(sBegin);    //"Dest"
            if(pos<0){
                sHead = src;}     //append
            else{   //replace
                sHead = src.substring(0, pos);
                int pos2 = src.indexOf(sEnding);  //">"
                if(pos2>=0){
                    sTail = src.substring(pos2); }
            }
            return (sHead + sSetting + sTail).trim();   
        }

        //
        public static String LenLimitation(String out, int limit)
        { 
            int len = out.length();
            if(len >= limit){
                out = out.substring(len - limit, len);
            }
            return out;
        }
    
        //在字符串"xxx, yyy, zzz... aaa"中去掉subString
        public static String Del(String sons, String son){
            sons += ",";
            sons.replaceAll(son + ",", "");
            //
            //int pos = sons.l.lastIndexOf(s);
            return sons;
        }
    
        // 替换为可打印字符　
        public static String ReplaceWithPrintable(String str)
        {
            if(str.isEmpty()){  
                 return"";  
             }  
            
             byte[] bOld =str.getBytes();  
             int bLength= bOld.length;  
             byte[] bNew = new byte[bLength];  
             for(int i =0;i<bLength;i++) {  
                
                int ub = KGet.unsignedByte(bOld[i]);   
                if((ub >=0 && ub <=31) || ub >=127){  
                     ub ='*';     //将不可打印字符至空  
                }  
               
                bNew[i]=(byte)ub;  
            }  
            
            return new String(bNew).toUpperCase();  
        }*/
 
    }
}
